package rexsee.script;

import java.util.ArrayList;
import java.util.HashMap;

public abstract class AbstractBlock {

	private final AbstractBlock parent;
	private final ArrayList<String> blocks;
	private final HashMap<String, Object> variables = new HashMap<String, Object>();

	public AbstractBlock(AbstractBlock parent, String script) {
		this.parent = parent;
		blocks = splitBlocks(script);
	}

	public final AbstractBlock getParent() {
		return parent;
	}
	public final String getScript() {
		String rtn = "";
		for (int i = 0; i < blocks.size(); i++) {
			rtn += blocks.get(i) + "<br><br>";
		}
		return rtn;
	}
	public final boolean defineVariable(String name) {
		if (variables.containsKey(name)) {
			return false;
		} else {
			variables.put(name, null);
			return true;
		}
	}
	public final boolean setVariable(String name, Object value) {
		if (variables.containsKey(name)) {
			variables.remove(name);
			variables.put(name, value);
			return true;
		} else if (parent != null) {
			return parent.setVariable(name, value);
		} else {
			return false;
		}
	}
	public final Object getVariable(String name) {
		if (variables.containsKey(name)) {
			return variables.get(name);
		} else if (parent != null) {
			return parent.getVariable(name);
		} else {
			return null;
		}
	}

	public abstract int getChildCount(int index);
	public abstract AbstractBlock getChild(int index);
	public abstract Object run();

	public static ArrayList<String> splitBlocks(String text) {
		ArrayList<String> blocks = new ArrayList<String>();
		text = text.trim();
		while (text.length() > 0) {
			int leftBrackets = text.indexOf("{");
			int semicolon = text.indexOf(";");
			int split = (leftBrackets > semicolon) ? semicolon : findRightBrackets(text, leftBrackets);
			if (split < 0) break;
			blocks.add(text.substring(0, split + 1));
			text = text.substring(split + 1);
		}
		return blocks;
	}
	private static int findRightBrackets(String str, int left) {
		int length = str.length();
		int number = 1;
		for (int i = left + 1; i < length; i++) {
			char c = str.charAt(i);
			if (c == '{') {
				number++;
			} else if (c == '}') {
				number--;
				if (number == 0) return i;
			}
		}
		return -1;
	}

}
